package com.gantang.poc.config;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.client.RestTemplate;

@Configuration
public class TestConfiguration {
    @Autowired
    ThreadPoolConfig threadPoolConfig;

    //定义线程池
    @Bean
    public ThreadPoolTaskExecutor threadPool() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(threadPoolConfig.getCorePoolSize());//线程池维护线程的最少数量
        threadPoolTaskExecutor.setMaxPoolSize(threadPoolConfig.getMaxPoolSize());//线程池维护线程的最大数量
        threadPoolTaskExecutor.setKeepAliveSeconds(300);//线程池维护线程所允许的空闲时间
        threadPoolTaskExecutor.setQueueCapacity(threadPoolConfig.getQueueCapacity());//线程池所使用的缓冲队列
        return threadPoolTaskExecutor;
    }

    @Bean
    public RestTemplate restTemplate() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(200); // 设置最大连接数
        connectionManager.setDefaultMaxPerRoute(50); // 设置每个路由的默认最大连接数
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(requestFactory);
    }

}
